<!DOCTYPE html>
<html>
    <head>
        <title>ann</title>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <script type="text/javascript"> 
            document.write("<sc" + "ript type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></scr" + "ipt>");
        </script> 
    <!--[if IE]><script type="text/javascript" src="http://code.google.com/p/explorercanvas/source/browse/trunk/silverlight/excanvas.js"></script><![endif]-->
        <script type="text/javascript" src="http://jquery.bassistance.de/treeview/jquery.treeview.js"></script>
        <script type="text/javascript" src="../src/anntree.min.js"></script>

        <link rel="stylesheet" href="http://jquery.bassistance.de/treeview/jquery.treeview.css" />
        <style>
        #kdStr {
            margin-right: 50%;
        }

        #graph {
            width: 50%;
            height: 700px;
            margin-left: 49%;
            border: 1px solid #ccc;
            position: absolute;
            top: 60px;
        }

        #init {
            position: absolute;
            width: 100%;
            height: 700px;
            z-index: 2;
        }

        #result {
            z-index: 1;
        }

        #cenLine {
            z-index: 3;
        }

        .copy {
            position: absolute;
            top: 0px;
            left: 0px;
            width: 100%;
            height: 700px;
        }

        .box {
            display: none;
        }

        </style>
    </head>
    <body>
    <h1 style="text-align: center;">ANN</h1>
    <h4>圖層：</h4>
    <p>
        <select id="layer">
            <option value="#init">初始資料</option>
            <option value="#result">分群結果</option>
        </select>
    </p>
    <h4>tree set：</h4>
    <ul>
    <li>bucket size：<input type="text" id="bkt" size="5" /></li>
        <li><p>split rule：
            <select id="spRule">
                <option value="midpt">mid plane</option>
            </select></p></li>
        <li><p>shrink rule：
            <select id="shRule">
                <option value="none">none</option>
                <option value="simple">simple</option>
            </select></p></li>
    <li style="display: inline;"><button id="resetTree">just only reset the tree</button></li>
        <li><p id="kdData">
            初始data：<br />
            <span name='dataInput'>
                <span>第1筆資料：</span>
                <input type="text" name="dataNum" size="5"/><span>個</span></span>
                <!--button id="addData">增加</button><button id="delData">減少</button><button id="setData">初始set data</button-->
            </p>
            <!--p id="addOneP">
                後來加入的data：
                <button id="addOne">增加</button><button id="submitAdd">確定加入</button></p-->
                <button id="resetData">reset data</button></li>
    </ul>
    <h4>search control：</h4>
    <ul>
        <li><p id="modeP">搜尋模式：
            <select id="mode">
                <option value="single">單點搜尋</option>
                <option value="box">範圍搜尋</option>
            </select></li>
            <ul>
            <li><p>希望得到的最近<input id="knn" type="text" size="5">個結果。
                <span class="box notLi">黑色為最近結果，其他為較遠的範圍內結果。</span></p></li>
                <li class="box isLi"><p class="box notLi">範圍設定：<br/>
                    長：<input id="bndW" type="text" size="5"/>px，
                    寬；<input id="bndH" type="text" size="5"/>px<br />
                </p></li>
            </ul>
        </p></li>
    </ul>
    <h4>theTree：</h4>
    <ul>
        <li><p id="kdStr">
            <ul id="theTree" class="treeview-gray treeview"></ul>
        </p></li>
    </ul>
    <p id="graph">
        <canvas id="init"></canvas>
        <canvas id="result" class="copy"></canvas>
        <canvas id="cenLine" class="copy"></canvas>
        <canvas id="query" class="copy"></canvas>
        <canvas id="move" class="copy"></canvas>
    </p>
    <script>
        (function(window){
            var _unitX;
            var _unitY;
            var theTree;
            var dataArray;
            var generateData = function(dataNum, dimDef) {
                var data = [];
                var dim = dimDef.length;
                var rand1 = Math.ceil(Math.random() * 7) + Math.ceil(Math.random() * 13);
                var rand2 = Math.ceil(Math.random() * 13) + Math.ceil(Math.random() * 37);
                var i;
                for (i = 0; i < Math.ceil(dataNum / 2); i++) {
                    var data_i = {};
                    for (var j = 0; j < dim; j++) {
                        var dim_j = dimDef[j];
                        data_i[dim_j] = Math.ceil(Math.random() * rand1) +
                                Math.ceil(Math.random() * rand2);
                    }
                    data.push(data_i);
                };


                rand1 = Math.ceil(Math.random() * 41) + Math.ceil(Math.random() * 31);
                rand2 = Math.ceil(Math.random() * 37) + Math.ceil(Math.random() * 23);
                for (i = Math.ceil(dataNum / 2); i < dataNum; i++) {
                    var data_i = {};
                    for (var j = 0; j < dim; j++) {
                        var dim_j = dimDef[j];
                        data_i[dim_j] = Math.ceil(Math.random() * rand1) +
                                Math.ceil(Math.random() * rand2);
                    }
                    data.push(data_i);
                };

                return data;
            };

            var redraw = function(annTest) {
                var initCanvas = document.getElementById('init');
                // draw init pts
                annTest.drawPts(initCanvas, 'DATA');

                theTree = annTest.getTree();
                // center line
                var cenLine = document.getElementById('cenLine');
                annTest.showCenLine(theTree, cenLine);

                var gpCanvas = document.getElementById('result');
                annTest.showGp(theTree, gpCanvas);

                var kdElm = document.getElementById('theTree');
                annTest.showLog(theTree, kdElm);
                $("#theTree").treeview();
                //var testpt = theTree.pa[5];
                //var ans = theTree.annkSearch(testpt);
                //console.log(theTree);
                //console.log(annTest);
                var nowMaxBound = theTree.bnd_max;
                var w = $("#cenLine").attr("width");
                var h = $("#cenLine").attr("height");
                _unitX = w / (nowMaxBound.x + 5);
                _unitY = h / (nowMaxBound.y + 5);
            };

            var init = function(dim) {
                var dataNumElm = $("input[name='dataNum']");
                var initNum = 80;
        var initBktSize = 4;
                dataNumElm[0].value = initNum;

                var bndWElm = $("#bndW");
                bndWElm[0].value = 100;
                var bndHElm = $("#bndH");
                bndHElm[0].value = 100;

                var knnElm = $("#knn");
                knnElm[0].value = 3;

                var bktElm = $("#bkt");
                bktElm[0].value = initBktSize;

                dataArray = generateData(initNum, dim);
                var selSp = $("#spRule");
                var selSpIdx = selSp[0].selectedIndex;
                var selSpVal = selSp[0].options[selSpIdx].value;
                var selSh = $("#shRule");
                var selShIdx = selSh[0].selectedIndex;
                var selShVal = selSh[0].options[selShIdx].value;
                //console.log('sp：' + selSpVal);
                //console.log('sh：' + selShVal);
                var treeSet = {};
                    treeSet.dimDef = dim;
                    treeSet.annSplit = selSpVal;
                    treeSet.annShrink = selShVal;
                    treeSet.bucketSize = initBktSize;
                var annTest = ann(dataArray, treeSet);
                return annTest;
            };

            var reset = function(annTest, dim, dataReset) {
                var resultCanvas = document.getElementById('query');
                var moveCanvas = document.getElementById('move');
                var w = $("#cenLine").attr("width");
                var h = $("#cenLine").attr("height");
                var ctx = resultCanvas.getContext('2d');
                var moveCtx = moveCanvas.getContext('2d');
                ctx.clearRect(0, 0, w, h);
                moveCtx.clearRect(0, 0, w, h);

                if (dataReset) {
                    var dataNumElm = $("input[name='dataNum']");
                    for (var i = 0; i < dataNumElm.length; i++) {
                        var dataNum_i = dataNumElm[i].value;
                        var data_i = generateData(dataNum_i, dim);
                        //dataArray.push(data_i);
                        dataArray = data_i;
                    }
                }

                var bktElm = $("#bkt");
                var selSp = $("#spRule");
                var selSpIdx = selSp[0].selectedIndex;
                var selSpVal = selSp[0].options[selSpIdx].value;
                var selSh = $("#shRule");
                var selShIdx = selSh[0].selectedIndex;
                var selShVal = selSh[0].options[selShIdx].value;
                //console.log('sp：' + selSpVal);
                //console.log('sh：' + selShVal);
                var treeSet = {};
                    treeSet.dimDef = dim;
                    treeSet.annSplit = selSpVal;
                    treeSet.annShrink = selShVal;
                    treeSet.bucketSize = parseInt(bktElm[0].value);
                annTest.init(dataArray, treeSet);
                theTree = annTest.bdTree();
                $("#theTree").empty();
                $("#kdLeft").empty();
                redraw(annTest);
            };

            window.onload = function(){
                var resultCanvas = document.getElementById('query');
                var moveCanvas = document.getElementById('move');
                resultCanvas.width = resultCanvas.clientWidth;
                resultCanvas.height = resultCanvas.clientHeight;
                moveCanvas.width = moveCanvas.clientWidth;
                moveCanvas.height = moveCanvas.clientHeight;
                var ctx = resultCanvas.getContext('2d');
                var moveCtx = moveCanvas.getContext('2d');
                var dimDef = ['x', 'y'];
                var annTest = init(dimDef);
                theTree = annTest.bdTree();
                redraw(annTest);

                $("#resetData").bind("click", function(){
                    var addDataElm = $("#addData");
                    var delDataElm = $("#delData");
                    var setDataElm = $("#setData");
                    var addOneP = $("#addOneP");
                    addDataElm.css("display", "inline");
                    delDataElm.css("display", "inline");
                    setDataElm.css("display", "inline");
                    addOneP.css("display", "none");
                    var input = $("[name='dataInput']");
                    for (var i = (input.length - 1); i > 0; i--) {
                        input.eq(i).remove();
                    }
                    reset(annTest, dimDef, 'dataReset');
                });
                $("#resetTree").bind("click", function(){
                    reset(annTest, dimDef);
                });
                $("#layer").bind("change", function(obj){
                    var selElm = obj.currentTarget;
                    var selectedIdx = selElm.selectedIndex;
                    var notSelected = (selectedIdx + 1) % 2;
                    var selOptElm = $(selElm.options[selectedIdx].value);
                    var notSelOptElm = $(selElm.options[notSelected].value);
                    selOptElm.css("zIndex", function(index, value){
                            return ++value;
                        });
                    notSelOptElm.css("zIndex", function(index, value){
                            return --value;
                        });
                });
                $("#mode").bind("change", function(obj) {
                    var selElm = obj.currentTarget;
                    var selectedIdx = selElm.selectedIndex;
                    var notSelected = (selectedIdx + 1) % 2;
                    var selVal = selElm.options[selectedIdx].value;
                    var boxElm = $(".isLi");
                    var otherBoxElm = $(".notLi");
                    switch(selVal) {
                        case 'box':
                            otherBoxElm.css("display", "inline");
                            boxElm.css("display", "list-item");
                            break;
                        default:
                            boxElm.css("display", "none");
                            otherBoxElm.css("display", "none");
                            break;
                    }
                });

                $("#cenLine").bind("mousemove", function(evt) {
                    var offsetX;
                    var offsetY;
                    if (evt.offsetX) {
                        offsetX = evt.offsetX;
                        offsetY = evt.offsetY;
                    } else {
                        offsetX = evt.layerX;
                        offsetY = evt.layerY;
                    }
                    var w = $("#cenLine").attr("width");
                    var h = $("#cenLine").attr("height");
                    var bndW = $("#bndW")[0].value;
                    var bndH = $("#bndH")[0].value;
                    var bndSize = {x: parseFloat(bndW), y: parseFloat(bndH)};
                    if (typeof bndSize.x != 'number' || bndSize.x <= 0) {
                        alert('輸入的範圍長度有誤，不得小於或等於0');
                        return;
                    }
                    if (typeof bndSize.y != 'number' || bndSize.y <= 0) {
                        alert('輸入的範圍寬度有誤，不得小於或等於0');
                        return;
                    }
                    var pt = {};
                    pt.x = (offsetX) /  _unitX;
                    pt.y = (offsetY) /  _unitY;
                    var selMode = $("#mode");
                    var selIdx = selMode[0].selectedIndex;
                    var selVal = selMode[0].options[selIdx].value;
                    moveCtx.clearRect(0, 0, w, h);
                    moveCtx.beginPath();
                    switch (selVal) {
                        case ('single'):
                            moveCtx.fillStyle = 'rgba(0, 0, 0, 1)';
                            moveCtx.arc(offsetX, offsetY, 3, 0, 2*Math.PI, false);
                            break;
                        case ('box'):
                            moveCtx.fillStyle = 'rgba(0, 0, 0, 0.2)';
                            moveCtx.rect((offsetX - bndSize.x / 2), (offsetY - bndSize.y / 2 ), bndSize.x, bndSize.y);
                            break;
                    }
                    moveCtx.fill();
                    moveCtx.closePath();
                });
                $("#cenLine").bind("click", function(evt) {
                    var offsetX;
                    var offsetY;
                    if (evt.offsetX) {
                        offsetX = evt.offsetX;
                        offsetY = evt.offsetY;
                    } else {
                        offsetX = evt.layerX;
                        offsetY = evt.layerY;
                    }
                    var w = $("#cenLine").attr("width");
                    var h = $("#cenLine").attr("height");
                    var bndW = $("#bndW")[0].value;
                    var bndH = $("#bndH")[0].value;
                    var bndSize = {x: parseFloat(bndW), y: parseFloat(bndH)};
                    var pt = {};
                    pt.x = offsetX /  _unitX;
                    pt.y = offsetY /  _unitY;
                    var selMode = $("#mode");
                    var selIdx = selMode[0].selectedIndex;
                    var selVal = selMode[0].options[selIdx].value;
                    var ans;
                    var knnElm = $("#knn");
                    var knn = parseInt(knnElm[0].value);
                    if (typeof knn != 'number' || knn < 0) {
                        alert('輸入的希望結果數目要大於0個歐~!!');
                        return;
                    }
                    var dd;
                    var nn_idx;
                    var ptLen;
                    ctx.clearRect(0, 0, w, h);
                    ctx.lineWidth = 2;
                    switch (selVal) {
                        case ('box'):
                            if (typeof bndSize.x != 'number' || bndSize.x <= 0) {
                                alert('輸入的範圍長度有誤，不得小於或等於0');
                                return;
                            }
                            if (typeof bndSize.y != 'number' || bndSize.y <= 0) {
                                alert('輸入的範圍寬度有誤，不得小於或等於0');
                                return;
                            }
                            var box_bnd = {
                                x: bndSize.x / _unitX,
                                y: bndSize.y / _unitY
                            };
                            var box = {q: pt, bndSize: box_bnd};
                            ctx.beginPath();
                            ctx.fillStyle = 'rgba(0, 153, 255, 0.2)';
                            ctx.strokeStyle = 'rgba(0, 153, 255, 0.2)';
                            ctx.rect((offsetX - bndSize.x / 2), (offsetY - bndSize.y / 2 ), bndSize.x, bndSize.y);
                            ctx.fill();
                            ctx.stroke();
                            ctx.closePath();
                            ans = theTree.annBoxSearch(box, knn);
                        case ('single'):
                            ctx.beginPath();
                            ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
                            ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';
                            ctx.arc(offsetX, offsetY, 4, 0, (2 * Math.PI), false);
                            ctx.fill();
                            ctx.stroke();
                            ctx.closePath();
                            if(selVal == 'single') {
                                ans = theTree.annkSearch(pt, knn);
                            }
                            break;
                    }
                    //console.log('pt：(' + pt.x + ' , ' + pt.y + ')');
                    //console.log('ans');
                    //console.log(ans);
                    dd = ans.dd;
                    nn_idx = ans.nn_idx;
                    var numInRange = (typeof ans.numInRange == 'number') ? ans.numInRange : -1;
                    ptLen = (numInRange >= 0) ? numInRange : knn;
                    if (ptLen == 0) {
                        alert('沒有符合的點歐~!!');
                    }
                    var radius = 5;
                    ctx.lineWidth = 1;
                    for (var i = 0; i < ptLen; i++) {
                        var nn_idx_i = nn_idx[i];
                        var dd_i = dd[i];
                        var pre_dd;
                        var ansPt_i = dataArray[nn_idx_i];
                        var ptx = ansPt_i.x * _unitX;
                        var pty = ansPt_i.y * _unitY;i
                        radius = 5;
                        if (i) {
                            pre_dd = dd[i - 1];
                            if (pre_dd == dd_i) {
                                radius += 1.5;
                            }
                        }
                        if (i < knn) {
                            ctx.strokeStyle = 'rgba(0, 0, 0, 1)';
                        } else {
                            ctx.strokeStyle = 'rgba(255, 0, 255, 1)';
                        }
                        //console.log('pt：(' + ptx + ' , ' + pty + ')');
                        //console.log('radius：' + radius);
                        ctx.beginPath();
                            ctx.arc(ptx, pty, radius, 0, (2 * Math.PI), false);
                            ctx.stroke();
                        ctx.closePath();
                    }
                });
            };
        })(window);
    </script>
    </body>
</html>
